<?php

    define('ROOT_PATH', dirname(__FILE__) . '/');
    
    require_once ROOT_PATH . 'dynamic/libs/common.fn.php';
    require_once ROOT_PATH . 'dynamic/libs/class.rudonSqlite.php';

    $protocol = (check_is_https())? 'https://': 'http://';
    define('LINK_ROOT', $protocol. $_SERVER['HTTP_HOST'].'/');
    

    /**
     * 数据库新建SQL
CREATE TABLE urls (
    id          INTEGER  PRIMARY KEY,
    status      INTEGER  DEFAULT (1),
    uid         INTEGER,
    create_time INTEGER,
    url_short   TEXT (6) NOT NULL,
    url_long    TEXT     NOT NULL,
    descp       TEXT
);
CREATE INDEX u ON urls (
    url_short
);
     */


    class urls {

        /* SQLite数据库文件地址 */
        public $db_file_path = ROOT_PATH . 'dynamic/db/db.db';

        /* SQLite数据库操作类 */
        public $db;


        // 构造函数
        public function __construct () {
            
            if (!file_exists($this->db_file_path)) {
                alert('数据库不存在');
            }
            $this->db = new rudonSqlite($this->db_file_path);
        }

        // 显示模版
        public function view ($name, $replaces_array = array()) {
            $fullpath = ROOT_PATH . 'dynamic/tpls/' . $name . '.html';
            if (!file_exists($fullpath)) {
                alert('模版不存在');
            }
            $c = file_get_contents($fullpath);

            // 替换
            if (is_array($replaces_array) && count($replaces_array)) {
                foreach ($replaces_array as $from => $to) {
                    $c = str_replace($from, $to, $c);
                }
            }

            echo $c;
            die();
        }

        // 显示首页
        public function action () {

            // 读数据
            if (isset($_GET['u']) && trim($_GET['u']) != '') {
                // 去掉引号
                $u = $_GET['u'];
                $u = str_replace('"', '', $u);
                $u = str_replace("'", '', $u);

                // 是否存在
                $sql = "select * from urls where url_short = '{$u}' limit 1";
                $dbres = $this->db->query($sql);
                if (count($dbres)) {
                    // 存在
                    $this->db->close_db();
                    $full = $dbres[0]['url_long'];
                    header('location:'.$full);
                    die();

                } else {
                    // 不存在
                    alert('<a href="/">No such record</a>');
                }
                return;
            }

            // 写数据
            if (isset($_POST['url']) && trim($_POST['url']) != '') {
                $u = $_POST['url'];
                $short = '';
                $full = '';

                // 去掉引号
                $u = str_replace('"', '', $u);
                $u = str_replace("'", '', $u);
                
                // 是否存在
                $sql = "select * from urls where url_long = '{$u}' limit 1";
                $dbres = $this->db->query($sql);
                if (count($dbres)) {
                    // 存在
                    $short = $dbres[0]['url_short'];
                    $full = LINK_ROOT . $short;
                    $this->db->close_db();

                } else {
                    // 不存在
                    $is_exists = false;
                    while (!$is_exists) {
                        // 获取随机六位字符
                        $short_rand = special_get_rand_string();

                        // 检查是否存在
                        // 是否存在
                        $sql = "select * from urls where url_short = '{$short_rand}' limit 1";
                        $dbres = $this->db->query($sql);
                        if (count($dbres)) {
                            // 存在
                            // 继续生成、直到找出不重复的短链接
                            
                        }  else {
                            // 不存在
                            $is_exists = true;
                            $short = $short_rand;
                            $full = LINK_ROOT . $short;
                        }
                    }

                    // 写入数据库
                    $now = time();
                    $sql = "insert into urls values(null, 1, 0, {$now}, '{$short}', '{$u}', '')";
                    $this->db->query($sql);
                    $this->db->close_db();
                    
                }

                // 展现模版
                $replaces = array(
                    '<a id="resultLink" href=""' => '<a id="resultLink" href="'.$full.'"',
                    '<span id="resultText"></span>' => '<span id="resultText">'.$full.'</span>'
                );
                $this->view('home', $replaces);

            }

            // 展现模版
            $this->view('home');
            
        }



    } // CLASS ENDING

    // 启动
    $app = new urls();
    $app->action();